package com.igd.interceptors;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.igd.action.BaseAction;
import com.igd.common.constant.RequestConstant;
import com.igd.pojo.vo.ExtData;
import com.igd.utils.CommonUtil;
import com.igd.utils.JsonUtil;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.opensymphony.xwork2.interceptor.PreResultListener;

/**
 * @createDate 2013-6-28
 *
 * @author QIAOYU
 *
 * @version 1.0
 *
 * @description 请求响应时对响应数据进行JSON格式转换
 */

public class ResponseJsonInterceptor extends AbstractInterceptor {

	private static final long serialVersionUID = 4478666265212684016L;

	private Logger logger = Logger.getLogger(this.getClass());
	
	public String intercept(ActionInvocation invocation) throws Exception {
		
		invocation.addPreResultListener(new PreResultListener(){

			public void beforeResult(ActionInvocation invocation, String arg1) {
				
				ActionContext ctx = invocation.getInvocationContext();
				
				BaseAction action = (BaseAction) invocation.getAction();
				
				Object o = ctx.get(RequestConstant.EXT_DATA_KEY);
				
				String jsonStr = null;
				
				/**此段判断如果是使用的ExtData作为ajax json返回对象则进行JSON处理,若不是则只进行一般的文本处理返回*/
				if(null != o && o instanceof ExtData){
					
					ExtData<?> extData = (ExtData<?>) o;
					
					if(null != extData){
						
						if(null != extData.getRspData()){
							
							extData.setRspDataSize(String.valueOf(extData.getRspData().size()));
							
						}
						
						if(StringUtils.isNotEmpty(extData.getMessage())){
							
							extData.setMessage(action.getText(extData.getMessage()));

						}
					}
					
					jsonStr = JsonUtil.toStandardJsonString(extData);
					
				}else{
					
					jsonStr = CommonUtil.getNullString(String.valueOf(o));

				}
				
				logger.info("response json string is:"+jsonStr);
				
				ctx.put(RequestConstant.EXT_DATA_KEY, jsonStr);
			}
		});
		
		return invocation.invoke();
	}
}
